'''
Author: your name
Date: 2021-04-20 10:26:47
LastEditTime: 2021-05-13 17:44:27
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: /tinyms/tinyms-api/apps/auth/organ/views.py
'''
from flask import render_template,request
from app import db
from . import auth_organ
from .model import Organ
from .service import OrganService

import json
import uuid
import time


@auth_organ.route('/save',methods = ['GET','POST'])
def save():
    data = {}
    if request.method == "POST":
        for key in request.form:
            data[key] = request.form.get(key)
    else:
        for key in request.args:
            data[key] = request.args.get(key)
    organ = Organ()
    organ.organ_code = data['organ_code']
    organ.organ_name = data['organ_name']
    organ.organ_jc = data['organ_jc']
    organ.organ_phone = data['organ_phone']
    organ.organ_address = data['organ_address']
    organ.organ_parent = data['organ_parent']
    organ.organ_status = data['organ_status']
    organ.organ_qhdm = data['organ_qhdm']
    organ.organ_qhmc = data['organ_qhmc']
    organ.owner_sys = data['owner_sys']
    organ.organ_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    if not data['organ_pk']:
        organ.organ_pk = str(uuid.uuid1())
        OrganService.save(organ)
    else:
        organ.organ_pk = data['organ_pk']
        OrganService.update(organ)
    data = {
        'msg':'保存成功',
        'code':'0',
    }
    return json.dumps(data,ensure_ascii=False)


@auth_organ.route('/tree_organ_lazy_list',methods=['GET','POST'])
def select():
    if request.method == "POST":
        organ_parent = request.form.get("organ_parent")  #获取页码
    else:
        organ_parent = request.args.get("organ_parent")
    organs = OrganService.list_all(organ_parent)
    # data = {
    #     'msg':'success',
    #     'code':0,
    #     'data':Organ.to_dict(organs)
    # }
    return json.dumps(Organ.to_dict(organs),ensure_ascii=False)

@auth_organ.route('/list',methods=['GET','POST'])
def list():
    # if request.method == "POST":
    #     organ_pk = request.form.get("organ_pk")  #获取页码
    # else:
    #     organ_pk = request.args.get("organ_pk")
    organs = OrganService.list()
    data = {
        'msg':'success',
        'code':0,
        'data':Organ.to_dict_ext(organs)
    }
    return json.dumps(data,ensure_ascii=False)

@auth_organ.route('/delete',methods=['GET','POST'])
def delete():
    if request.method == "POST":
        organ_pk = request.form.get("organ_pk")  #获取页码
    else:
        organ_pk = request.args.get("organ_pk")
    organs = OrganService.delete(organ_pk)
    data = {
        'msg':'删除成功',
        'code':0,
        'data':""
    }
    return json.dumps(data,ensure_ascii=False)